package com.tfleo.mealssenger.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.github.ignition.core.widgets.RemoteImageView;
import com.tfleo.mealssenger.Main;
import com.tfleo.mealssenger.R;
import com.tfleo.mealssenger.object.Food;

import android.content.Context;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

public class WantedListAdapter extends ArrayAdapter<Food> {
	private LayoutInflater mInflater;
	private Context mContext;
	
	private boolean mIsMine; //to indicate whether this is my page
	private int mUserId;
	private String mAuth;
	
	public WantedListAdapter(Context context, int resource, int textViewResourceId, 
			List<Food> objects, LayoutInflater inflater, boolean isMine, int userId, String auth) {
		super(context, resource, textViewResourceId, objects);
		mInflater = inflater;
		mContext = context;
		mIsMine = isMine;
		mUserId = userId;
		mAuth = auth;
	}
	
	@Override
    public View getView(int position, View convertView, ViewGroup parent) {   
		ViewHolder holder = null;
		final TextView name;
		TextView location = null;
		CheckBox check = null;
		RemoteImageView image = null;
		
		final Food food = getItem(position);
		
		if(convertView == null) {
			convertView = mInflater.inflate(R.layout.wishlist_entry, null);
			holder = new ViewHolder(convertView);
			convertView.setTag(holder);
		}

		holder = (ViewHolder) convertView.getTag();
		
		image = holder.getImageView();
		image.setImageUrl(food.imageUrl);
		image.loadImage();
		
		name = holder.getNameView();
		name.setText(food.name);
		
		location = holder.getLocationView();
		location.setText(food.locationName);
		
		check = holder.getCheckboxView();
		if(!mIsMine) {
			check.setVisibility(View.INVISIBLE);
			check.setEnabled(false);
		} else {
			check.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
			        if(((CheckBox) v).isChecked()) {
			        	ChangeWishTask task = new ChangeWishTask();
						task.execute(mUserId, food.id, 1);
						name.setPaintFlags(name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
			        } else {
			        	ChangeWishTask task = new ChangeWishTask();
						task.execute(mUserId, food.id, 0);
						name.setPaintFlags(name.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
			        }
				}
			});
			
			if(check.isChecked()) {
				name.setPaintFlags(name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
			}
		}

		return convertView;
	}
	
	private boolean updateWishList(int userId, int foodId, int done) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(Main.SERVER_URL + "wanted/done");

		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("user_id", Integer.toString(userId)));
			nameValuePairs.add(new BasicNameValuePair("food_id", Integer.toString(foodId)));
			nameValuePairs.add(new BasicNameValuePair("done", Integer.toString(done)));
			nameValuePairs.add(new BasicNameValuePair("auth", mAuth));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String responseBody = httpclient.execute(httppost, responseHandler);
			JSONObject response = new JSONObject(responseBody);
			if(response.getInt("code") > 0) {
				return true;
			} else {
				return false;
			}
		} catch(Exception e){
			e.printStackTrace();
		}

		return false;
	}
	
	private class ViewHolder {
		private View vRow;
		private TextView vName = null;
		private TextView vLocation = null;
		private RemoteImageView vImage = null;
		private CheckBox vCheckbox = null;

		public ViewHolder(View row) {
			vRow = row;
		}

		public TextView getNameView() {
			if (vName == null) {
				vName = (TextView) vRow.findViewById(R.id.name);
			}
			return vName;
		}
		
		public TextView getLocationView() {
			if(vLocation == null) {
				vLocation = (TextView) vRow.findViewById(R.id.location);
			}
			return vLocation;
		}

		public RemoteImageView getImageView() {
			if (vImage == null) {
				vImage = (RemoteImageView) vRow.findViewById(R.id.img);
			}
			return vImage;
		}
		
		public CheckBox getCheckboxView() {
			if (vCheckbox == null) {
				vCheckbox = (CheckBox) vRow.findViewById(R.id.done_check);
			}
			return vCheckbox;
		}
	}
	
	private class ChangeWishTask extends AsyncTask<Integer, Void, Boolean> {
		int mPos;
		boolean mRsvp;
		@Override
		protected Boolean doInBackground(Integer... data) {
			return updateWishList(data[0], data[1], data[2]);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				
			} else {

				Toast.makeText(mContext, "Error: Server request failed", Toast.LENGTH_SHORT).show();
			}
		}	
	}
}
